<template>
  <van-form @submit="onSubmit">
    <van-field
        v-model="editUser.currentValue"
        :name="editUser.editKey"
        :label="editUser.editName"

    />
    <van-uploader
        v-model="fileList"
        name="file"
        :upload-text="uploadText"
        :max-count="1"
        accept="image/*"
    />
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import { ref } from "vue";
import myAxios from "../../plugins/myAxios.ts";
import {Toast} from "vant";
import {getCurrent} from '../../services/currentUser.ts';

const route = useRoute();
const router = useRouter();

const editUser = ref({
  editKey: route.query.editKey,
  currentValue: route.query.currentValue,
  editName: route.query.editName,
})
const fileList = ref([]);
const uploadText = ref("上传图片");

const onSubmit = async () => {
  const currentUser = await getCurrent();

  if (!currentUser) {
    Toast.fail('用户未登录');
    return;
  }

  console.log(currentUser, '当前用户')

  // 获取上传的文件对象
  const file = fileList.value[0];
  if (!file) {
    Toast.fail("请先上传图片");
    return;
  }
  const formData = new FormData();
  formData.append("file", file.file);
  const res = await myAxios.post('/user/update/avatar', formData,{
    headers: {
      "Content-Type": "multipart/form-data",
    },

  })
  console.log(res, '更新请求');
  if (res.code === 0 && res.data > 0) {
    Toast.success('修改成功');
    router.back();
  } else {
    Toast.fail('修改错误');
  }
};

</script>

<style scoped>

</style>
